package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

/**
 * Finds this computer's ip address.
 * 
 * @author Jason
 * 
 */
public class IPLocater {

	private static final String ERROR = "Error";

	private static String ip = null;

	/**
	 * Gets the IP address of this server.
	 */
	public static String getIP() {
		if (ip == null) {
			InetAddress addr;
			try {
				addr = InetAddress.getLocalHost();
				// Get IP Address
				byte[] ipAddr = addr.getAddress();
				StringBuffer sb = new StringBuffer();
				sb.append(ipAddr[0] + ".");
				sb.append(ipAddr[1] + ".");
				sb.append(ipAddr[2] + ".");
				sb.append(ipAddr[3]);
				ip = sb.toString();
			} catch (UnknownHostException e) {
			}
		}
		if (ip == null) {
			ip = getIPFromSite();
			if (ip == null)
				ip = JOptionPane
						.showInputDialog("Failed to retrieve your IP address. Please enter it below:");
		}
		return ip;
	}

	private static String getIPFromSite() {
		String ip;
		try {
			URL whatIsMyIP = new URL("http://www.whatismyip.org");
			URLConnection conn = whatIsMyIP.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			ip = reader.readLine();
			reader.close();
			if (ip.contains(ERROR)) {
				return null;
			}
			return ip;
		} catch (IOException e) {
			return null;
		}
	}

}
